package com.shenmazong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shenmazong.config.DayNumConfig;
import com.shenmazong.dto.TbCompany;
import com.shenmazong.dto.TbCompanyJob;
import com.shenmazong.mapper.TbCompanyJobMapper;
import com.shenmazong.mapper.TbSoftwareMapper;
import com.shenmazong.config.MqConfig;
import com.shenmazong.config.MyOssUtils;
import com.shenmazong.service.TbCompanyService;
import com.shenmazong.mapper.TbCompanyMapper;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.vo.BatchChooseIdVo;
import com.shenmazong.vo.CompanyJobVo;
import com.shenmazong.vo.CompanyVo;
import com.shenmazong.vo.ListParamVo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 */
@Service
public class TbCompanyServiceImpl extends ServiceImpl<TbCompanyMapper, TbCompany>
implements TbCompanyService{
    @Autowired
    private TbCompanyMapper tbCompanyMapper;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private TbCompanyJobMapper tbCompanyJobMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private TbSoftwareMapper tbSoftwareMapper;
    @Override
    public ResultResponse findAllCompanyStudent(ListParamVo listParamVo) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<b style='color:red;'>").postTags("</b>").field("companyName");
        boolQuery.must(QueryBuilders.rangeQuery("deleteFlag").lte(0));
        if (!StringUtils.isEmpty(listParamVo.getParamMap().get("companyName"))){
            boolQuery.must(QueryBuilders.multiMatchQuery(listParamVo.getParamMap().get("companyName"),"companyName"));
        }
        if (!StringUtils.isEmpty(listParamVo.getParamMap().get("startTime"))){
            boolQuery.must(QueryBuilders.rangeQuery("createTime").gte(listParamVo.getParamMap().get("startTime")));
        }
        if (!StringUtils.isEmpty(listParamVo.getParamMap().get("endTime"))){
            boolQuery.must(QueryBuilders.rangeQuery("createTime").lte(listParamVo.getParamMap().get("endTime")));
        }
        if (!StringUtils.isEmpty(listParamVo.getParamMap().get("softwareId"))){
            boolQuery.must(QueryBuilders.termQuery("softwareId",listParamVo.getParamMap().get("softwareId")));
        }
        NativeSearchQuery build = builder.withPageable(PageRequest.of(listParamVo.getCurrent()-1, listParamVo.getSize())).withQuery(boolQuery)
                .withHighlightBuilder(highlightBuilder).build();
        SearchHits<CompanyVo> hits = elasticsearchRestTemplate.search(build, CompanyVo.class);
        Page<CompanyVo> page = new Page<>();
        ArrayList<CompanyVo> list = new ArrayList<>();
        for (SearchHit<CompanyVo> hit : hits) {
            CompanyVo content = hit.getContent();
            if (hit.getHighlightField("companyName").size()>0){
                content.setCompanyName(hit.getHighlightField("companyName").get(0));
            }
            list.add(content);
        }
        page.setCurrent(listParamVo.getCurrent());
        page.setSize(listParamVo.getSize());
        page.setTotal(hits.getTotalHits());
        page.setRecords(list);
        return ResultResponse.SUCCESS(page);
    }

    @Override
    public ResultResponse saveCompany(CompanyVo companyVo) {
        try {
            TbCompany company = new TbCompany(null,companyVo.getCompanyName(),companyVo.getCompanyRecommend()
            ,companyVo.getCompanyAddress(),companyVo.getCompanyImg(),companyVo.getCompanyTel(),companyVo.getCompanyUrl(),
            null,null,null,null,null,companyVo.getSoftwareId(),null);
            tbCompanyMapper.insert(company);
            List<CompanyJobVo> list = companyVo.getList();
            for (CompanyJobVo jobVo : list) {
                TbCompanyJob job = new TbCompanyJob(company.getCompanyId(), jobVo.getJobId(), jobVo.getJobNum(), jobVo.getJobSalary(),
                        jobVo.getSalaryNum(), jobVo.getCompanyNegotiable(), null, null, null);
                tbCompanyJobMapper.insert(job);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap<String, String> map = new HashMap<>();
            companyVo.setSoftwareName(tbSoftwareMapper.selectById(company.getSoftwareId()).getSoftwareName());
            companyVo.setCompanyId(company.getCompanyId());
            companyVo.setCreateTime(company.getCreateTime());
            companyVo.setDeleteFlag(company.getDeleteFlag());
            map.put("saveCompany",objectMapper.writeValueAsString(companyVo));
            amqpTemplate.convertAndSend(MqConfig.BOTIAN_EXCHANGE,MqConfig.COMPANY_KEY,objectMapper.writeValueAsString(map));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponse.FAILED();
        }
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse updateCompany(CompanyVo companyVo) {
        try {
            TbCompany tbCompany = tbCompanyMapper.selectById(companyVo.getCompanyId());
            tbCompany.setCompanyName(companyVo.getCompanyName());
            tbCompany.setCompanyRecommend(companyVo.getCompanyRecommend());
            tbCompany.setCompanyAddress(companyVo.getCompanyAddress());
            tbCompany.setCompanyImg(companyVo.getCompanyImg());
            tbCompany.setCompanyTel(companyVo.getCompanyTel());
            tbCompany.setCompanyUrl(companyVo.getCompanyUrl());
            tbCompany.setSoftwareId(companyVo.getSoftwareId());
            tbCompany.setSyncEs((byte) 0);
            tbCompanyMapper.updateById(tbCompany);
            List<CompanyJobVo> list = companyVo.getList();
            tbCompanyJobMapper.delete(new QueryWrapper<TbCompanyJob>().lambda().eq(TbCompanyJob::getCompanyId,tbCompany.getCompanyId()));
            for (CompanyJobVo vo : list) {
                TbCompanyJob job = new TbCompanyJob(tbCompany.getCompanyId(), vo.getJobId(), vo.getJobNum(), vo.getJobSalary(),
                        vo.getSalaryNum(), vo.getCompanyNegotiable(), null, null, null);
                tbCompanyJobMapper.insert(job);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap<String, String> map = new HashMap<>();
            map.put("saveCompany",objectMapper.writeValueAsString(companyVo));
            String s = objectMapper.writeValueAsString(map);
            amqpTemplate.convertAndSend(MqConfig.BOTIAN_EXCHANGE,MqConfig.COMPANY_KEY,s);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponse.FAILED();
        }
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse deleteCompany(BatchChooseIdVo batchChooseIdVo) {
        if (batchChooseIdVo.getIds().size()==0){
            return ResultResponse.FAILED("至少选择一个哟");
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap<String, String> map = new HashMap<>();
            for (Long id : batchChooseIdVo.getIds()) {
                map.put("delCompany",objectMapper.writeValueAsString(id));
                String s = objectMapper.writeValueAsString(map);
                amqpTemplate.convertAndSend(MqConfig.BOTIAN_EXCHANGE,MqConfig.COMPANY_KEY,s);
                tbCompanyMapper.deleteById(id);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponse.FAILED();
        }
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse uploadFile(MultipartFile file) {
        return MyOssUtils.uploadFileObjectStorage(file);
    }

}




